package com.guli.auth.service.impl;
/*
 * @Author 罗
 * @date 2020/10/18 - 3:54 下午
 */

import com.guli.auth.feign.MemberServiceFeignClient;
import com.guli.auth.service.RegisterService;
import com.guli.auth.vo.UserVo;
import com.guli.common.constant.AuthServerConstant;
import com.guli.common.pojo.vo.StatusCodeEnum;
import com.guli.common.utils.R;
import com.guli.mall.serviceBase.globalException.MallException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class RegisterServiceImpl implements RegisterService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    MemberServiceFeignClient memberServiceFeignClient;

    @Override
    public R register(UserVo userVo) {

        String verificationCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.VERIFICATION_CODE_PREFIX + userVo.getPhoneNumber());

        if(StringUtils.isEmpty(verificationCode)||!verificationCode.equals(userVo.getVerificationCode())){
           throw new MallException(StatusCodeEnum.EXPIRE_VERIFICATION_CODE);
        }

        // TODO 生产环境记得打开注释
        // 删除 redis key
        stringRedisTemplate.delete(AuthServerConstant.VERIFICATION_CODE_PREFIX + userVo.getPhoneNumber());

        Map<String, String> userMap = new HashMap<>();

        userMap.put("username",userVo.getUsername());

        userMap.put("password",userVo.getPassword());

        userMap.put("mobile",userVo.getPhoneNumber());

        R r = memberServiceFeignClient.addUser(userMap);

        if(r.getCode().equals(StatusCodeEnum.SUCCESS.getCode())){
            log.info("注册用户：{}，成功",userVo);
        }

        return r;

    }
}
